<template>
	<div class="container">
		<h2 style="text-align: center;">{{ id ? '修改' : '创建' }}物资申请</h2>
		<a-form ref="formRef" :model="formState" layout="vertical" @finish="savePurchase">
			<a-row :gutter="20">
				<a-col :span="12">
					<a-form-item label="选择项目" name="project_id" :rules="{ required: true, message: '请选择项目' }">
						<a-select v-model:value="formState.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="送达地址" name="deliver_address" :rules="{ required: true, message: '请输入送达地址' }">
						<a-input v-model:value="formState.deliver_address" readonly="readonly" placeholder="请输入送达地址" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="接收联系人" name="receiver_id" :rules="{ required: true, message: '请选择接收联系人' }">
						<a-select v-model:value="formState.receiver_id" :show-search="true" placeholder="请选择接收联系人" :options="userlist" option-filter-prop="label" @change="changeUser"></a-select>
					</a-form-item>
				</a-col>
				<!--				<a-col v-show="false" :span="12">-->
				<!--					<a-form-item label="接收联系人" name="receiver" :rules="{ required: true, message: '请输入接收联系人' }">-->
				<!--						<a-input v-model:value="formState.receiver" placeholder="请输入接收联系人" />-->
				<!--					</a-form-item>-->
				<!--				</a-col>-->
				<a-col :span="12">
					<a-form-item label="联系人电话" name="receiver_tel" :rules="{ required: true, message: '请输入联系人电话' }">
						<a-input v-model:value="formState.receiver_tel" placeholder="请输入联系人电话" readonly="readonly" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="送达日期" name="deliver_time" :rules="{ required: true, message: '请输入送达日期' }">
						<a-date-picker v-model:value="formState.deliver_time" value-format="YYYY-MM-DD HH:mm:ss" show-time style="width:100%" />
					</a-form-item>
				</a-col>

				<a-col :span="24">
					<h4>本次采购物资清单</h4>
					<div class="table-toolbar mb-3">
						<a-space>
							<a-button type="primary" @click="addMaterialModel">
								<plus-outlined />新增
							</a-button>

							<!--
							<a-button class="cache-btn" @click="handleCache">
								<DeliveredProcedureOutlined />保存
							</a-button>
							-->
						</a-space>
					</div>

					<a-table v-if="type == 1" :data-source="formState.materials" :columns="planMaterialColumns" :row-key="(record) => record.key" :pagination="false">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'id'">{{ index + 1 }}</template>
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择材料名称' }">
									<a-tree-select v-model:value="formState.materials[index].source_id" :show-search="true" placeholder="请选择材料名称" allow-clear tree-default-expand-all :tree-data="sourceOptions" tree-node-filter-prop="label" style="width:100%" @change="handleSourceChange(record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[index].id" :show-search="true" placeholder="请选择" :options="modelOptions[record.source_id]" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="handleModelChange(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[index].unit" :show-search="true" placeholder="请选择" :options="unitOptions[record.id]" :field-names="{ value: 'name' }" style="width:100%" @change="changeUnit(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" @blur="checkqty(record)" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
					<a-table v-if="type == 2" :data-source="formState.materials" :columns="planMaterialColumns1" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择周转料名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" :show-search="true" placeholder="请选择周转料名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[record.key].id" :show-search="true" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="(id) => changeModel(id, record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[record.key].unit" :show-search="true" placeholder="请选择" :options="unitOptions" :field-names="{ value: 'name' }" style="width:100%" @change="changeUnit(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']" :rules="{ required: true, message: '请输入计划租赁时长' }">
									<a-input v-model:value="formState.materials[index].use_time" placeholder="请输入计划租赁时长" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'time_unit'">
								<a-form-item :name="['materials', index, 'time_unit']" :rules="{ required: true, message: '请选择时长计量单位' }">
									<a-select v-model:value="formState.materials[index].time_unit" :show-search="true" placeholder="请选择时长计量单位" :options="timeunitOptions" :field-names="{ value: 'name' }" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
					<a-table v-if="type == 3" :data-source="formState.materials" :columns="planMaterialColumns2" :row-key="(record) => record.key">
						<template #bodyCell="{ column, record, index }">
							<template v-if="column.dataIndex === 'name'">
								<a-form-item :name="['materials', index, 'source_id']" :rules="{ required: true, message: '请选择机械设备名称' }">
									<a-tree-select v-model:value="formState.materials[record.key].source_id" :show-search="true" placeholder="请选择机械设备名称" allow-clear tree-default-expand-all :tree-data="materialOptions" tree-node-filter-prop="label" style="width:100%" @change="(id) => changeMaterial(id, record)">
										<template #title="{ label }">{{ label }}</template>
									</a-tree-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'model'">
								<a-form-item :name="['materials', index, 'id']" :rules="{ required: true, message: '请选择规格' }">
									<a-select v-model:value="formState.materials[record.key].id" :show-search="true" placeholder="请选择" :options="materialModelOptions[record.source_id] || []" allow-clear :field-names="{ value: 'id', label: 'model' }" style="width:100%" @change="(id) => changeModel(id, record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'unit'">
								<a-form-item :name="['materials', index, 'unit']" :rules="{ required: true, message: '请选择计量单位' }">
									<a-select v-model:value="formState.materials[record.key].unit" :show-search="true" placeholder="请选择" :options="unitOptions" :field-names="{ value: 'name' }" style="width:100%" @change="changeUnit(record)"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'quantity'">
								<a-form-item :name="['materials', index, 'quantity']" :rules="{ required: true, message: '请输入数量' }">
									<a-input-number v-model:value="formState.materials[index].quantity" placeholder="请输入数量" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_time'">
								<a-form-item :name="['materials', index, 'use_time']" :rules="{ required: true, message: '请输入计划租赁时长' }">
									<a-input v-model:value="formState.materials[index].use_time" placeholder="请输入计划租赁时长" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'time_unit'">
								<a-form-item :name="['materials', index, 'time_unit']" :rules="{ required: true, message: '请选择时长计量单位' }">
									<a-select v-model:value="formState.materials[index].time_unit" :show-search="true" placeholder="请选择时长计量单位" :options="timeunitOptions" :field-names="{ value: 'name' }" style="width:100%"></a-select>
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'memo'">
								<a-form-item :name="['materials', index, 'memo']">
									<a-input v-model:value="formState.materials[index].memo" placeholder="请输入备注" />
								</a-form-item>
							</template>
							<template v-else-if="column.key === 'operation'">
								<a-space>
									<a-popconfirm title="确定要删除当前材料吗？" ok-text="是" cancel-text="否" @confirm="deleteMaterialModel(record.key)">
										<a-button type="link" style="color:#ff7875">
											<delete-outlined />删除
										</a-button>
									</a-popconfirm>
								</a-space>
							</template>
						</template>
					</a-table>
				</a-col>
				<a-col :span="24" style="margin-top: 24px;">
					<a-form-item label="备注" name="memo">
						<a-textarea v-model:value="formState.memo" :auto-size="{ minRows: 4, maxRows: 6 }"></a-textarea>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<!--
						<a-button class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />保存
						</a-button>
						-->

						<a-button v-if="!formState.id || ![0,1,2].includes(formState.workflow_status)" type="primary" html-type="submit">
							<save-outlined />保存
						</a-button>

						<a-workflow v-if="formState.id" v-model:status="formState.workflow_status" module="purchase" :target-id="formState.id" :project-id="formState.project_id" :code="formState.code" :user-id="formState.purchaser_id" @submit="submitPurchase"></a-workflow>

						<a-button @click="closeTab('/purchase')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { DeleteOutlined, SaveOutlined, DeliveredProcedureOutlined, CloseOutlined, PlusOutlined } from "@ant-design/icons-vue";
import { AWorkflow } from "@/components";

//import { baseURL } from "../utils/request";
//import dayjs from "dayjs";
import { post, listToTree, postJson } from "../utils";
import { useRoute, useRouter } from "vue-router";
import { add, subtract } from "@/utils/operation.js";
//缓存数据
const handleCache = () => {
	// console.log(formState.value);
	localStorage.setItem("purchase-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};
const route = useRoute();
const router = useRouter();

const id = computed(() => {
	return route.params.id || 0;
});
const formState = ref({ materials: [] });
const contractlist = ref([]); //	合同列表
const userlist = ref([]); // 供应商列表
const formRef = ref();
const type = ref("1");
const { proxy } = getCurrentInstance();
const addMaterialModel = () => {
	formState.value.materials.push({ key: formState.value.materials.length });
};

const planMaterialColumns = [
	{
		title: "物资名称",
		dataIndex: "name",
		width: 200,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 150,
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "合同剩余量",
		dataIndex: "pendingQuantity",
		width: 100,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	}
];
const planMaterialColumns1 = [
	{
		title: "ID",
		dataIndex: "key",
		width: 60,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text + 1;
		}
	},
	{
		title: "周转料名称",
		dataIndex: "name",
		width: 130,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 130,
		ellipsis: true
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "需用数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "计划租赁时长",
		dataIndex: "use_time",
		width: 100,
		align: "center"
	},
	{
		title: "时长单位",
		dataIndex: "time_unit",
		width: 100,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	}
];
const planMaterialColumns2 = [
	{
		title: "ID",
		dataIndex: "key",
		width: 60,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text + 1;
		}
	},
	{
		title: "机械设备名称",
		dataIndex: "name",
		width: 130,
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		width: 130,
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		width: 130,
		align: "center"
	},
	{
		title: "配置数量",
		dataIndex: "quantity",
		width: 100,
		align: "center"
	},
	{
		title: "计划租赁时长",
		dataIndex: "use_time",
		width: 100,
		align: "center"
	},
	{
		title: "时长计量单位",
		dataIndex: "time_unit",
		width: 100,
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		width: 200,
		align: "center"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	}
];

//projectOptions
const projectOptions = ref([]);
post("department/projects?type=3").then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			leader: d.leader,
			phone: d.phone,
			address: d.address
		};
	});
});

const handleSourceChange = record => {
	record.id = undefined;
	record.unit = undefined;
};

const handleModelChange = record => {
	record.unit = undefined;
};
const changeUnit = async record => {
	if (record.id) {
		const materialIds = formState.value.materials.filter(item => item.id === record.id);
		if (materialIds.length > 1) {
			proxy.$message.error("请勿选择相同的物料");
			record.id = null;
			record.unit = null;
		}
		const contractMaterialInfos2MaterialId = contractlist.value.reduce((target, item) => {
			for (const material of item.materials) {
				if (!target[material.id]) {
					target[material.id] = 0;
				}
				target[material.id] = add([target[material.id], material.ContractMaterial?.pending_quantity || 0]);
			}
			return target;
		}, {});
		record.pendingQuantity = contractMaterialInfos2MaterialId[record.id];
	}
};

const materialInfo = ref({});
const sourceOptions = ref([]);
const modelOptions = ref({});
const unitOptions = ref({});
const changeProject = project_id => {
	formState.value.receiver_id = null;
	return new Promise((resolve, reject) => {
		Promise.all([
			getUserOptions(project_id),
			getMaterialOptions(project_id),
		]).then(() => resolve())
	});
};

const getUserOptions = async project_id => {
	return post("project/user", { project_id, scene: "main", status: "1" }).then(data => {
		userlist.value = data.map(d => ({
			label: d.fullname || d.username,
			value: d.id,
			mobile: d.mobile
		}));
	});
};

const getMaterialOptions = project_id => {
	return postJson("contract/apply", { project_id, types: [1, 2], material_types: [1, 3] }).then(data => {
		materialInfo.value = {};
		sourceOptions.value = [];
		modelOptions.value = {};
		unitOptions.value = {};

		if (!data.length) {
			contractlist.value = [];
			formState.value.project_id = null;
			proxy.$message.error("当前项目尚未绑定合同");
			return;
		}

		contractlist.value = data;

		// 物资唯一 按照物资分组统计
		const materials = data
			.map(item => item.materials)
			.reduce((res, curr) => {
				res.push(...curr);
				return res;
			}, []);
		materialInfo.value = materials.reduce((res, curr) => {
			//过滤混凝土
			if (curr.source_id === 3 || curr.parent_id === 3) return res;

			if (!res[curr.id]) {
				const model = curr.attr ? `${curr.model}（${curr.attr}）` : curr.model;
				res[curr.id] = {
					name: curr.name,
					model: model, // 型号
					unit: curr.ContractMaterial.unit, // 单位 物资中的单位有问题，显示为id
					source_id: curr.source_id, // 字典物料id
					quantity: 0 // 当前物资数量
				};
			}
			// 物资数量汇总
			const quantity = Number(curr.ContractMaterial.quantity);
			res[curr.id].quantity += isNaN(quantity) ? 0 : quantity;
			return res;
		}, {});

		sourceOptions.value = Object.keys(materialInfo.value)
			.map(materialId => {
				return {
					value: materialInfo.value[materialId].source_id,
					label: materialInfo.value[materialId].name
				};
			})
			.reduce((res, curr) => {
				const ids = res.map(item => item.value);
				if (!ids.includes(curr.value)) {
					res.push(curr);
				}
				return res;
			}, []);

		const sourceIds = sourceOptions.value.map(item => item.value);
		modelOptions.value = sourceIds.reduce((res, sourceId) => {
			const materialIds = Object.keys(materialInfo.value).filter(materialId => materialInfo.value[materialId].source_id === sourceId);
			res[sourceId] = materialIds.map(materialId => {
				return {
					id: Number(materialId),
					model: materialInfo.value[materialId].model
				};
			});
			return res;
		}, {});

		unitOptions.value = Object.keys(materialInfo.value).reduce((res, materialId) => {
			res[materialId] = [
				{
					name: materialInfo.value[materialId].unit,
					label: materialInfo.value[materialId].unit
				}
			];
			return res;
		}, {});

		//自动完善地址信息
		const projectInfo = projectOptions.value.find(d => d.value === project_id);
		// formState.value.receiver = null;
		// formState.value.receiver_tel = null;
		// formState.value.deliver_address = null;
		// if (!projectInfo.address || !projectInfo.phone || !projectInfo.leader) {
		// 	proxy.$message.error("请到组织架构完善当前项目信息");
		// 	formState.value.project_id = null;
		// 	return resolve();
		// }
		// formState.value.receiver = projectInfo.leader;
		// formState.value.receiver_tel = projectInfo.phone;
		formState.value.deliver_address = projectInfo.address;

		return;
	});
};

const changeUser = userId => {
	const user = userlist.value.find(d => d.value === userId);
	formState.value.receiver = user.label;
	formState.value.receiver_tel = user.mobile;
};

//检验数量
const checkqty = async record => {
	if (record.id > 0) {
		if (record.quantity > record.pendingQuantity) {
			proxy.$message.error("预约清单数量不能超过合同剩余量");
			record.quantity = record.pendingQuantity;
		}
		if (parseFloat(record.quantity) === 0) {
			record.quantity = null;
		}
		//当前的物资数量
		// let current_qty = 0;
		// formState.value.materials.map(d => {
		// 	if (d.id === record.id) {
		// 		current_qty = current_qty + parseFloat(d.quantity);
		// 	}
		// });
		// const purchaseHistory = await post("purchase/all", { project_id: formState.value.project_id, material_ids: JSON.stringify([record.id]) });
		// const history_current_qty = purchaseHistory.reduce((target, item) => {
		// 	if (parseInt(item.id) === parseInt(route.params.id)) return target;
		// 	for (const material of item.materials) {
		// 		if (material.id !== record.id) {
		// 			continue;
		// 		}
		// 		target = target + parseFloat(material.PurchaseMaterial.quantity);
		// 	}
		// 	return target;
		// }, 0);
		// // 当前物料的合同数量
		// const material = materialInfo.value[record.id];
		// if (current_qty > material.quantity - history_current_qty) {
		// 	proxy.$message.error("预约清单数量不能超过合同数量");
		// 	let now_qty = parseFloat(material.quantity) - parseFloat(history_current_qty) - parseFloat(current_qty) + parseFloat(record.quantity);
		// 	if (now_qty < 0) {
		// 		now_qty = 0;
		// 	}
		// 	record.quantity = now_qty;
		// }
	}
};
onMounted(async () => {
	/*
	const cacheData = localStorage.getItem("purchase-save");
	formState.value = JSON.parse(cacheData) || formState.value;
	*/

	if (id.value) {
		post("purchase/info", { id: id.value }).then(async data => {
			await changeProject(data.project.id);
			const contractMaterialInfos2MaterialId = contractlist.value.reduce((target, item) => {
				for (const material of item.materials) {
					if (!target[material.id]) {
						target[material.id] = 0;
					}
					target[material.id] = add([target[material.id], material.ContractMaterial?.pending_quantity || 0]);
				}
				return target;
			}, {});
			data.materials = data.materials.map(item => {
				const { quantity, unit, memo } = item.PurchaseMaterial;
				const pendingQuantity = contractMaterialInfos2MaterialId[item.id];
				return {
					...item,
					quantity,
					unit,
					memo,
					pendingQuantity
				};
			});
			formState.value = data;
		});
	} else if (formState.value?.project_id) {
		const { project_id } = formState.value;

		getUserOptions(project_id);
		getMaterialOptions(project_id);
	}
});

const savePurchase = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };

			if (!contractlist.value.length) {
				proxy.$message.error("当前项目尚未绑定合同");
				return;
			}

			if (!params.materials.length) {
				proxy.$message.error("请添加材料清单");
				return;
			}

			// 判断所有物资不能超过合同
			const sourceIds = params.materials.map(item => item.source_id);
			const targetSourceIds = Object.keys(materialInfo.value).map(materialId => materialInfo.value[materialId].source_id);
			if (sourceIds.some(sourceId => !targetSourceIds.includes(sourceId))) {
				proxy.$message.error("只能选择合同内的物资");
				return;
			}
			// 2. 判断物资数量
			const summaryRes = params.materials.reduce((res, curr) => {
				if (!res[curr.id]) {
					res[curr.id] = {
						quantity: 0
					};
				}
				res[curr.id].quantity += Number(curr.quantity);
				return res;
			}, {});

			const isValid = Object.keys(summaryRes).every(materialId => {
				return summaryRes[materialId].quantity <= materialInfo.value[materialId].quantity;
			});
			if (!isValid) {
				proxy.$message.error("物资数量不能超过合同数量");
				return;
			}

			params.materials = JSON.stringify(
				params.materials.map(({ id, unit, quantity, memo }) => {
					return {
						id,
						unit,
						quantity,
						memo
					};
				})
			);

			params.contract_ids = contractlist.value.map(item => item.id).join(",");

			const { id, project_id, deliver_address, receiver_id, contract_ids, receiver_tel, deliver_time, materials, receiver, memo } = params;

			post("purchase/save", {
				id,
				project_id,
				deliver_address,
				contract_ids,
				receiver_id,
				receiver_tel,
				deliver_time,
				materials,
				receiver,
				memo
			})
				.then(data => {
					if (id) {
						proxy.$message.success("采购单修改成功", 1);
					} else {
						proxy.$message.success("采购单创建成功", 1);
						router.push(`/purchase/edit/${data?.id}`);
					}

					/*
					closeTab("/purchase");
					localStorage.removeItem("purchase-save");
					*/
				})
				.catch(err => {
					console.log(err);

					proxy.$message.error(err);
				});
		})
		.catch(err => {
			proxy.$message.error(err.message);
		});
};

const submitPurchase = () => {
	proxy.$message.success("采购单提交成功", 1);
	closeTab("/purchase");
};

const materialOptions = ref([]);

const materialModelOptions = ref({});
const changeMaterial = (id, record) => {
	//强制选择规格
	record.id = null;

	if (!id) return;

	post("material", { source_id: id, page_size: 10000 }).then(({ data }) => {
		materialModelOptions.value[id] = data.map(d => {
			if (d.attr) d.model = `${d.model}（${d.attr}）`;

			return d;
		});
	});
};
/**
const copyMaterialModel = record => {
	formState.value.materials.push({ ...record, key: formState.value.materials.length });
}; */

const deleteMaterialModel = key => {
	const { materials } = formState.value;

	const index = materials.findIndex(d => d.key === key);
	if (index === false) return;
	materials.splice(index, 1);

	formState.value = {
		...formState.value,
		materials: materials.map((d, i) => {
			d.key = i;
			return d;
		})
	};
};

//调用父页面closeTab方法
/*
//父页面定义closeTab方法
provide("closeTab", path => {
	
});
*/
const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}

	h3 {
		line-height: 40px;
		font-size: 16px;
		font-weight: 400;
		margin-bottom: 20px;

		display: flex;
		align-items: center;

		&:before {
			content: "";
			display: block;
			width: 2px;
			height: 20px;
			background: rgb(24, 144, 255);
			margin-right: 10px;
		}
	}

	h4 {
		font-weight: 600;
		margin: 15px 0;
		line-height: 30px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>
